package com.zxy.supplier_system.server.entity

import jakarta.persistence.*
import org.hibernate.annotations.ColumnDefault
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import org.springframework.security.core.userdetails.UserDetails
import java.time.OffsetDateTime

@Entity
@EntityListeners(AuditingEntityListener::class)
@Table(
    uniqueConstraints = [
        UniqueConstraint(
            name = "phone_number_system_service_id_uindex",
            columnNames = ["phoneNumber", "system_service_id"]
        )
    ]
)
class Employee : UserDetails {

    companion object {
        const val MAX_PASSWORD_LENGTH = 16
        const val INITIAL_PASSWORD_LENGTH = 8
        const val MIN_PASSWORD_LENGTH = INITIAL_PASSWORD_LENGTH
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int? = null

    lateinit var name: String

    @Column(length = 11)
    lateinit var phoneNumber: String

    @Column(length = MAX_PASSWORD_LENGTH)
    private lateinit var password: String

    @ManyToOne(cascade = [CascadeType.ALL])
    @JoinColumn
    var wechatUserInfo: WechatUserInfo?= null

    @OneToMany(
        mappedBy = "employee",
        cascade = [CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REMOVE, CascadeType.REFRESH],
        orphanRemoval = true
    )
    var roles: MutableList<EmployeeRole> = mutableListOf()

    @CreatedDate
    lateinit var createdDateTime: OffsetDateTime

    @ManyToOne
    @JoinColumn
    @CreatedBy
    var createdBy: Employee? = null

    @ManyToOne
    @JoinColumn
    lateinit var systemService: SystemService

    @OneToMany(mappedBy = "employee")
    var marketOrders: MutableList<MarketOrder> = mutableListOf()

    @OneToMany(mappedBy = "user", cascade = [CascadeType.PERSIST,CascadeType.MERGE])
    var jwtTokenMetadataList: MutableList<JwtTokenMetadata> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var createdCheckInventoryRecords:MutableList<CheckInventoryRecord> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var createdDirectSaleOrders:MutableList<DirectSaleOrder> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var createdProcurements:MutableList<Procurement> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var createdProcurementReturns:MutableList<Procurement> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var createdMarketCheckInventoryRecords:MutableList<MarketCheckInventoryRecord> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var marketReturnOrders:MutableList<MarketReturnOrder> = mutableListOf()

    @OneToMany(mappedBy = "createdBy")
    var marketSaleDocuments: MutableList<MarketSaleDocument> = mutableListOf()

    /**
     * 作为卖场业务员管理的卖场
     */
    @OneToMany(mappedBy = "saleManager")
    var managedMarkets: MutableList<Market> = mutableListOf()

    /**
     * 作为促销员所在的卖场
     */
    @OneToMany(mappedBy = "employee")
    var guidedMarket: MutableList<MarketShoppingGuide> = mutableListOf()

    @ColumnDefault(value = "1")
    @Column(nullable = false)
    var enabled: Boolean = true

    override fun getAuthorities(): List<Authority> {
        return roles.map { it.role }.flatMap { it.authorities }
    }

    override fun getPassword(): String {
        return password
    }

    fun setPassword(password: String) {
        this.password = password
    }

    override fun getUsername(): String {
        return id.toString()
    }

    override fun isAccountNonExpired(): Boolean {
        return true
    }

    override fun isAccountNonLocked(): Boolean {
        return true
    }

    override fun isCredentialsNonExpired(): Boolean {
        return true
    }

    override fun isEnabled(): Boolean {
        return this.enabled
    }

    @OneToOne( optional = false, cascade = [CascadeType.ALL], orphanRemoval = true, mappedBy = "employee")
    lateinit var setting: EmployeeSetting

}